<?php

namespace app\shop\controller;


use app\shop\model\ShopExpress;
use app\shop\model\ShopGoodsSpec;
use app\shop\model\ShopOrderExpress;
use app\common\service\Status;
use buildView\Button;
use buildView\Filter;
use buildView\TimeLine;
use think\Controller;
use buildView\Detail;
use buildView\Form;
use buildView\Grid;
use app\shop\model\ShopOrder;

/**
 * 订单管理
 * Class Order
 * @package app\admin\controller
 */
class Order extends Controller
{
    /**
     * 列表
     * @auth true
     * @menu true
     * @return string
     */
    public function index()
    {

        $grid = new Grid(new ShopOrder);
        $grid->setTitle('订单列表');
        $grid->setFromOpen();
        $grid->user()->userInfo();

        $grid->user()->nickname('会员昵称')->hide();
        $grid->order_no('订单编号')->hide();
        $grid->title('订单标题')->hide();
        $grid->status('订单状态')->using(Status::ORDERSTATUS())->hide();
        $grid->total_price('订单金额')->hide();
        $grid->pay_price('已支付金额')->hide();
        $grid->create_at('下单时间')->hide();
        $grid->pay_time('支付时间')->hide();

        $grid->status('订单信息')->display(function ($val, $data, $html) {
            if (is_null($data['pay_time'])) {
                $pay_time = '--';
            } else {
                $pay_time = $data['pay_time'];
            }

            $html = "订单编号：<strong class='color-text'>{$data['order_no']}</strong><br>订单状态：{$html}<br>订单金额：<strong class='color-blue'>{$data['total_price']}</strong>&nbsp;&nbsp;已支付：<strong class='color-blue'>{$data['pay_price']}</strong><br>下单时间：{$data['create_at']}<br>支付时间：{$pay_time}";
            return $html;
        })->align('left')->excelClose()->using(Status::ORDERSTATUS())->badge();
        $grid->goods_record('商品信息')->display(function ($vals, $data) {
            $htmlArr = [];
            foreach ($vals as $val) {
                $htmlArr[] = "<p>{$val['good_title']}</p><p>{$val['spec_name']}</p><p class='color-desc'>售价：{$val['price']} 元 数量：{$val['num']}</p>";
            }
            $html = implode('<hr>', $htmlArr);
            return $html;
        })->minWidth(300)->setExcelData(function ($vals,$data){
            $html = '';
            foreach ($vals as $val) {
                $html .= "{$val['good_title']} {$val['spec_name']} 售价：{$val['price']} 元 数量：{$val['num']} ";
            }
            return $html;
        })->align('left');

        $grid->address_info('发货信息')->display(function ($val, $data) {
            if ($data['express_type'] == 1) {
                $remind = '';
                if($data['is_remind'] == 1){
                    $remind = '<span class="layui-badge">提醒发货</span>';
                }
                $html = $remind."<p>姓名：{$val['name']}&nbsp;&nbsp;手机号：{$val['phone']}</p><p>地址：{$val['province']}{$val['city']}{$val['area']}{$val['address']}</p>";
                if (!empty($data['express']['id'])) {
                    $html .= "<p class=''>快递公司: {$data['express']['company']}</p>";
                    $button = new Button('物流追踪', 'normal', 'xs', '');
                    $button->href(url('tracking') . '?express_id=' . $data['express']['id'], 'modal');
                    $html .= $button->render();

                }
                if ($data['status'] == 2) {
                    $button = new Button('修改发货信息', 'primary', 'xs', '');
                    $button->href(url('updateAddress') . '?id=' . $data['id'], 'modal');
                    $html .= $button->render();
                }
                if ($data['status'] == 2 || $data['status'] == 3) {
                    if (empty($data['express']['id'])) {
                        $express_title = '填写物流信息';
                    } else {
                        $express_title = '修改物流信息';
                    }
                    $button = new Button($express_title, '', 'xs');
                    $button->href(url('delivery') . '?order_id=' . $data['id'] . '&id=' . $data['express']['id'], 'modal');
                    $html .= $button->render();
                }
            } else {
                $html = "<p>自提联系电话：{$val['phone']}</p><p>自提地址：{$val['province']}{$val['city']}{$val['area']}{$val['address']}</p>";
            }
            return $html;
        })->setExcelData(function ($val,$data){
            if ($data['express_type'] == 1) {
                $html = "姓名：{$val['name']} 手机号：{$val['phone']} 地址：{$val['province']}{$val['city']}{$val['area']}{$val['address']}";
            }else{
                $html = "自提联系电话：{$val['phone']} 自提地址：{$val['province']}{$val['city']}{$val['area']}{$val['address']}";
            }
            return $html;
        })->minWidth(300)->align('left');
        $grid->actions(function ($action, $data) {
            $action->hideEdit();
            $action->hideDel();
            if ($data['pay_type'] == 2 && $data['is_pay'] == 0 && $data['status'] == 1) {
                $button = new Button('已支付','normal','sm','layui-icon-rmb');
                $button->href(url('updatePayPrice') . '?id=' . $data['id'], 'modal');
                $action->append($button);
            }
        });
        $grid->filter(function (Filter $filter) {
            $filter->like('user.nickname', '会员');
            $filter->eq('order_no', '订单号');
            $filter->eq('type', '订单类型')->select(Status::SHOPTYPE());
            $filter->eq('status', '订单状态')->select(Status::ORDERSTATUS());
            $filter->eq('express_type', '配送方式')->select(Status::EXPRESSTYPE());
            $filter->eq('pay_type', '支付方式')->select(Status::PAYTYPE());
            $filter->dateBetween('create_at', '下单时间');
        });
        $grid->hideDeletesButton();
        $grid->hideAddButton();
        return $grid->view();
    }
    public function remind_num(){
        $count = ShopOrder::where('express_type',1)->where('status',2)->count();
        $stock_warning = sysconf('stock_warning');
        $stock_num = ShopGoodsSpec::whereRaw('stock-sale < '.$stock_warning)->where('is_deleted',0)->count('DISTINCT gid');
        $this->success('成功','',[
            'order_num'=>$count,
            'stock_num'=>$stock_num,
        ]);
    }
    /**
     * 线下支付
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/10/8 11:30
     */
    public function updatePayPrice()
    {
        $form = new Form(new ShopOrder);
        $form->number('pay_price','支付金额')->min(0)->required();
        $form->saving(function ($post,$data){
            $post['pay_time'] = date('Y-m-d H:i:s');
            $post['is_pay'] = 1;
            if($data['express_type'] == 1){
                $post['status'] = 2;
            }else{
                $post['delivery_time'] = date('Y-m-d H:i:s');
                $post['status'] = 3;
            }
            return $post;
        });
        return $form->view();
    }

    /**
     * 修改发货信息
     * @auth true
     * @menu true
     */
    public function updateAddress()
    {
        $form = new Form(new ShopOrder());
        $form->text('address_info.name', '姓名')->required();
        $form->text('address_info.phone', '手机号')->phone()->required();
        $form->distpicker(['address_info.province', 'address_info.city', 'address_info.area'], '地区')->required();
        $form->text('address_info.address', '详情地址')->required();
        $form->saving(function ($post, $model) {
            $post['address_info']['province'] = $post['address_info_province'];
            $post['address_info']['city'] = $post['address_info_city'];
            $post['address_info']['area'] = $post['address_info_area'];
            $model->json(['address_info'])->strict(false)->update($post);
        });
        return $form->view();
    }

    /**
     * 物流追踪
     * @auth true
     * @menu true
     * @return string
     */
    public function tracking()
    {
        $express_id = $this->request->get('express_id');
        $express = ShopOrderExpress::find($express_id);
        $data = \library\tools\Express::query($express['mark'], $express['number']);
        $data = $data['data'];
        if (empty($data)) {
            $data = [
                [
                    'time' => date('Y-m-d H:i:s'),
                    'context' => '查询不到信息',
                ]
            ];
        }
        $timeLine = new TimeLine($data, 'time', 'context');
        return $timeLine->render();
    }

    /**
     * 发货
     * @auth true
     * @menu true
     * @return string
     */
    public function delivery()
    {
        $form = new Form(new ShopOrderExpress());
        $form->hidden('order_id', 'order_id')->default($this->request->get('order_id'));
        $wuliu = ShopExpress::where('is_deleted', 0)->column('express_title', 'id');
        $form->select('express_id', '快递公司')->options($wuliu)->required();
        $form->text('number', '快递单号')->required();
        $form->saving(function ($post) {
            $wuliu = ShopExpress::get($post['express_id']);
            $post['company'] = $wuliu['express_title'];
            $post['mark'] = $wuliu['express_code'];
            $order = ShopOrder::where('id', $post['order_id'])->find();
            $order->delivery_time = date('Y-m-d H:i:s');
            $order->status = 3;
            $order->save();

            return $post;
        });
        return $form->view();
    }

    /**
     * 详情
     * @auth true
     * @menu true
     * @return string
     */
    public function detail()
    {
        $detail = new Detail(new ShopOrder);
        $detail->setTitle('订单详情');
        $data = $detail->getModelData();
        $detail->layout('订单信息', 6, function ($detail) {
            $detail->type('订单类型')->using(Status::SHOPTYPE());
            $detail->order_no('订单号');
            $detail->freight_price('快递费');
            $detail->goods_price('商品总价');
            $detail->total_price('订单金额');
            $detail->is_pay('支付状态')->display(function ($val,$data,$html){
                if ($data['pay_type'] == 2 && $data['is_pay'] == 0 && $data['status'] == 1) {
                    $button = new Button('已支付','normal','sm','layui-icon-rmb');
                    $button->href(url('updatePayPrice') . '?id=' . $data['id'], 'modal');
                    $html = $button->render();
                }
                return $html;
            })->using(Status::PAYSTATUS())->badge();
            $detail->pay_type('支付方式')->using(Status::PAYTYPE());
            $detail->pay_no('微信流水号');
            $detail->pay_price('支付金额￥');
            $detail->pay_time('支付时间');
            $detail->status('订单状态')->using(Status::ORDERSTATUS())->badge();
            $detail->create_at('下单时间');
        })->layout('会员信息', 6, function ($detail) {
            $detail->user()->nickname('会员昵称');
            $detail->user()->headimg('会员头像')->image(50, 50, 50);
        })->layout('发货信息', 6, function (Detail $detail) use ($data) {
            if ($data['express_type'] == 1) {
                $detail->address_info()->name('姓名');
                $detail->address_info()->phone('联系电话');
                $detail->address_info('地址')->display(function ($val) {
                    return "{$val['province']}{$val['city']}{$val['area']}{$val['address']}";
                });
                if ($data['status'] == 2) {
                    $detail->column('express', '')->display(function ($val, $data) {
                        $html = '';
                        $button = new Button('修改发货信息', 'primary', 'xs', '');
                        $button->href(url('updateAddress') . '?id=' . $data['id'], 'modal');
                        $html .= $button->render();
                        if ($data['status'] == 2 || $data['status'] == 3) {
                            if (empty($data['express']['id'])) {
                                $express_title = '填写物流信息';
                            } else {
                                $express_title = '修改物流信息';
                            }
                            $button = new Button($express_title, '', 'xs', '');
                            $button->href(url('delivery') . '?order_id=' . $data['id'] . '&id=' . $data['express']['id'], 'modal');
                            $html .= $button->render();

                        }
                        return $html;
                    });
                }
            } else {
                $detail->address_info()->phone('自提联系电话');
                $detail->address_info('自提地址')->display(function ($val) {
                    return "{$val['province']}{$val['city']}{$val['area']}{$val['address']}";
                });
            }

        });
        if (!empty($data['express']['id'])) {
            $detail->layout('物流信息', 6, function (Detail $detail) {
                $detail->express()->company('快递公司');
                $detail->express()->number('快递单号');
                $detail->express()->id('')->display(function ($val, $data) {
                    $button = new Button('物流追踪', 'normal', 'xs', '');
                    $button->href(url('tracking') . '?express_id=' . $data['express']['id'], 'modal');
                    $html = $button->render();
                    return $html;
                });
            });
        }
        if ($data['type'] == 4) {
            $detail->layout('拼团信息', 6, function (Detail $detail) {
                $detail->spell()->status('拼团状态')->using(Status::SPELLTATUS());
                $detail->spell()->num('成团人数');
                // $detail->spell()->join_num('当前人数');
                $detail->spell()->q_num('缺少人数')->display(function ($val, $data) {
                    return $data['spell']['num'] - $data['spell']['join_num'];
                });
                $detail->spell()->start_time('拼团开始时间');
                $detail->spell()->end_time('拼团结束时间');
            });
        }
        $detail->hasManyArray('goods_record', '商品信息', 12, function ($detail) {
            $detail->spec_img('商品规格图')->image();
            $detail->spec_name('商品规格');
            $detail->good_title('商品标题');
            $detail->price('商品售价');
            $detail->num('数量');
        });
        $sepll = $data['spell'];
        if($sepll){
            $detail->hasManyArray('sepllOrder', '拼团成员', 12, function ($detail) use ($sepll) {
                $detail->user()->headimg('头像')->image(5);
                $detail->user()->nickname('昵称')->display(function ($val, $data) use ($sepll) {
                    if ($sepll['uid'] == $data['uid']) {
                        return "{$val} <span class='layui-badge'>团长</span>";
                    } else {
                        return $val;
                    }
                });
                $detail->order_no('订单编号')->display(function ($val, $data) {
                    $button = new Button($val, '', 'xs');
                    $button->href(url('order/detail') . '?back=1&id=' . $data['id']);
                    return $button->render();
                });
                $detail->create_at('加入时间');

            });
        }
        return $detail->view();
    }


}
